﻿using System;
using System.Net;
using Microsoft.WindowsAzure.StorageClient;

namespace Demo.TableStorageDataServices.Web.Models
{
    public class OuSuisJeBlobs
    {
        public CloudBlobContainer BlobContainer { get; set; }

        public OuSuisJeBlobs(CloudBlobContainer blobcontainer)
        {
            BlobContainer = blobcontainer;
        }

        public bool CreateBlobFromStream(System.IO.Stream str, String BlobName)
        {
            var blob = BlobContainer.GetBlockBlobReference(BlobName);
            blob.UploadFromStream(str);
            return true;
        }

        public bool CreateBlobFromByte(byte[] bytes, String blobName)
        {
            var blob = BlobContainer.GetBlockBlobReference(blobName);
            blob.UploadByteArray(bytes);
            return true;
        }


        public System.IO.Stream GetBlobStream(String BlobName)
        {

            CloudBlockBlob blob = BlobContainer.GetBlockBlobReference(BlobName);
            var str = new System.IO.MemoryStream();
            blob.DownloadToStream(str);
            return str;
        }

        public bool IsExist(String blobName)
        {
            CloudBlockBlob blob = BlobContainer.GetBlockBlobReference(blobName);
            try
            {

                blob.FetchAttributes();
                return true;
            }

            catch (StorageClientException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return false;
                }
                throw ex;
            }
        }
    }
}
